package com.hc.kotlin_coroutine

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.lang.Exception
import kotlin.coroutines.coroutineContext

fun main5() = runBlocking<Unit> {
    launch {
        printInfo()
    }
}
suspend fun printInfo(){
    delay(1000)
    println("Hello World "+ coroutineContext)
}
fun main6() = runBlocking {
    repeat(50){
        launch {
            delay(3000)
            println("."+coroutineContext)
        }
    }
}
fun main7() = runBlocking<Unit> {
    GlobalScope.launch { //全局协程像守护线程
        repeat(50){
            delay(500)
            println("sleeping ${it}")
        }
    }
    delay(1300)
}
fun main8() = runBlocking {//runBlocking会等待协程体和所有子协程结束
    launch {
        repeat(10){
            delay(500)
            println("sleeping ${it}")
        }
    }
    delay(1300)
}
fun main9() = runBlocking<Unit> {
    val job = launch {
        repeat(10){
            try {
                delay(500)
            }catch (e:Exception){
                println(e) //协程取消时会抛出异常 该异常被认为是正常的 不添加try catch也是可行的
            }
            println("sleeping ${it}")
        }
    }
    delay(1300)
    println("try to cancel")
    job.cancel() //协程取消执行
    println("quit")
}
fun main10() = runBlocking<Unit> {
    var startTime = System.currentTimeMillis()
    val job = launch(Dispatchers.Default){
        var nextTime = startTime
        var i = 0
        while (i < 5){ //正在计算 且没有挂起函数 协程取消无效
            if(System.currentTimeMillis() >= nextTime){
                println("sleeping ${i++}")
                nextTime += 500
            }
        }
    }
    delay(1300)
    println("try to cancel")
    job.cancelAndJoin()
    println("quit")
}
fun main() = runBlocking<Unit> {
    var startTime = System.currentTimeMillis()
    val job = launch(Dispatchers.Default){
        var nextTime = startTime
        var i = 0
        while (isActive){ //显示检查协程的取消 协程可取消
            if(System.currentTimeMillis() >= nextTime){
                println("sleeping ${i++}")
                nextTime += 500
            }
        }
    }
    delay(1300)
    println("try to cancel")
    job.cancelAndJoin()
    println("quit")
}